﻿function datebox_onblur(sender, event) {
    if (!validateUSDate(sender))
        sender.value = "";
}
function validateUSDate(sender) {
    /*********************************************

    Ex. mm/dd/yyyy or mm-dd-yyyy or mm.dd.yyyy
    /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/

    **********************************************/

    //Format: dd/mm/yyyy
    var strValue = sender.value;
    var objRegExp = /^\d{1,2}(\/)\d{1,2}\1\d{4}$/

    //check to see if in correct format
    if (!objRegExp.test(strValue))
        return false; //doesn't match pattern, bad date
    else {
        var strSeparator = "/";
        var arrayDate = strValue.split(strSeparator);

        arrayDate[0] = "00" + arrayDate[0];
        arrayDate[0] = arrayDate[0].substr(arrayDate[0].length - 2);
        arrayDate[1] = "00" + arrayDate[1];
        arrayDate[1] = arrayDate[1].substr(arrayDate[1].length - 2);

        //create a lookup for months not equal to Feb.
        var arrayLookup = { '01': 31, '03': 31,
            '04': 30, '05': 31,
            '06': 30, '07': 31,
            '08': 31, '09': 30,
            '10': 31, '11': 30, '12': 31
        }
        var intDay = parseInt(arrayDate[0], 10);
        var intMonth = parseInt(arrayDate[1], 10);
        var intYear = parseInt(arrayDate[2], 10);

        if (intYear < 2200) {
            intYear += 543;
            arrayDate[2] = intYear;
        }

        //check if month value and day value agree
        if (arrayLookup[arrayDate[1]] != null) {
            if (intDay <= arrayLookup[arrayDate[1]] && intDay != 0) {
                sender.value = arrayDate.join("/");
                return true; //found in lookup table, good date
            }
        }

        if (intMonth == 2) {
            if (intDay > 0 && intDay < 29) {
                sender.value = arrayDate.join("/");
                return true;
            }
            else if (intDay == 29) {
                if ((intYear % 4 == 0) && (intYear % 100 != 0) ||
			 (intYear % 400 == 0)) {
                    // year div by 4 and ((not div by 100) or div by 400) ->ok
                    sender.value = arrayDate.join("/");
                    return true;
                }
            }
        }
    }
    return false; //any other values, bad date
}